<template>
  <div class="mainBox">
    <el-button type="primary" round @click="adddialog = true" style="margin-bottom: 10px;">
      发帖
    </el-button>
    <div v-for="(item, index) in List.data" v-bind:key="index">
      <div class="rrr" style="justify-content: space-between;border-bottom: 0.8px rgb(229, 229, 229) solid;
                        border-left: 0.8px rgb(229, 229, 229) solid;border-right: 0.8px rgb(229, 229, 229) solid;">
        <div class="rrr" v-if="item != null" style="width: 100%;">
          <div class="ccc" style="padding: 15px 0 15px 10px;">
            <img style="height: 88px;width: 88px;border-radius: 10%;" src="@\assets\images\background.png" />
            <label style="display: flex;justify-content: center;text-align: center;font-size: 12px;font-weight: 700;">
              {{ item.user.nickName }}
            </label>
          </div>
          <div class="text_container ccc" style="padding: 0 0 8px 20px;width: 100%;">
            <div class="ccc" style="padding: 20px 20px 0 0;width: 100%;height: 100%;gap: 4px;">
              <div>
                {{ item.title }}
              </div>
              <div v-for="(img, index) in item.img" v-bind:key="index">
                <img style="height: 88px;width: 88px;border-radius: 5;" :src="ImgUrl + img" />
              </div>
            </div>
            <div class="rrr" style="color: #999;justify-content: right;
                                    align-items: center; text-align: center;height: 28px;width: 100%;font-size: 12px;">
              <div class="rrr" style="gap: 5px;">
                <el-tag type="primary">鱼：{{ item.fishType }}</el-tag>
                <el-tag type="primary">钓竿：{{ item.diaogan }}</el-tag>
                <el-tag type="success">鱼饵：{{ item.yuer }}</el-tag>
              </div>
              <div style="margin: 0 4px;">
                {{ utils.getFormatDate(item.create_time) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="sizeList"
      layout="total, sizes, prev, pager, next, jumper" :total="List.total" @size-change="sizeChange"
      @current-change="pageChange" />
  </div>
  <el-dialog v-model="adddialog" title="发布帖子" width="500" draggable>
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="标题" prop="title">
        <el-input type="textarea" v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="鱼的种类" prop="fish">
        <el-select v-model="form.fishTypeIndex" placeholder="Select" size="large" style="width: 240px">
          <el-option v-for="item in fishOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-if="form.fishTypeIndex == '其他'" type="text" v-model="form.fishType"
          placeholder="请输入鱼的种类"></el-input>
      </el-form-item>
      <el-form-item label="钓竿" prop="diaogan">
        <el-select v-model="form.diaoganIndex" placeholder="Select" size="large" style="width: 240px">
          <el-option v-for="item in diaoganOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-if="form.diaoganIndex == '其他'" type="text" v-model="form.diaogan" placeholder="请输入钓竿"></el-input>
      </el-form-item>
      <el-form-item label="鱼饵" prop="yuer">
        <el-select v-model="form.yuerIndex" placeholder="Select" size="large" style="width: 240px">
          <el-option v-for="item in yuerOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-if="form.yuerIndex == '其他'" type="text" v-model="form.yuer" placeholder="请输入鱼饵"></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="img">
        <el-upload action="http://localhost:5000/file/upload" :multiple="true" :on-success="handleUploadSuccess"
          :before-upload="beforeAvatarUpload" :on-remove="handleRemove" :file-list="imgList" list-type="picture-card"
          :limit=9>
          <template #trigger>
            <el-button size="small" type="primary">点击上传</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="adddialog = false">取消</el-button>
        <el-button type="primary" @click="addNewPosts()">
          新增
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useStore } from "vuex";

const store = useStore();
let ImgUrl = store.state.user.ImgUrl;
const api = require("@/utils/api.js");
const utils = require("../../utils/utils.js");
// const userId = 1
const userId = store.state.user.isLoggedIn ? store.state.user.userInfo.id : null;
console.log(userId)
let List = ref([])
let currentPage = ref(1)
let sizeList = ref([10, 20, 50, 100])
let pageSize = ref(10)
const adddialog = ref(false)
const getData = async () => {
  await api.get('/getDisscuss', { pageNum: currentPage.value, pageSize: pageSize.value }).then(res => {
    List.value = res.data.data;
    for (let i = 0; i < List.value.data.length; i++) {
      if (List.value.data[i].img != null) {
        List.value.data[i].img = List.value.data[i].img.split(",")
      } else {
        List.value.data[i].img = []
      }
    }
    console.log(List.value)
  }).catch(error => {
    console.log(error)
  })
}
onMounted(async () => {
  await getData()
});

const pageChange = async (page) => {
  currentPage.value = page;
  await getData()
}

const sizeChange = async (size) => {
  pageSize.value = size;
  await getData()
}
let fishOption =  require("../../../public/fishs.json")
let diaoganOption = [
  {
    value: '溪流竿',
    label: '溪流竿',
  },
  {
    value: '台钓竿',
    label: '台钓竿',
  },
  {
    value: '海竿',
    label: '海竿',
  },
  {
    value: '矶竿',
    label: '矶竿',
  },
  {
    value: '路亚竿',
    label: '路亚竿',
  },
  {
    value: '其他',
    label: '其他',
  }
]
let yuerOption = [{ 'value': '蚯蚓', 'label': '蚯蚓' },
{ 'value': '红虫', 'label': '红虫' },
{ 'value': '河虾', 'label': '河虾' },
{ 'value': '玉米', 'label': '玉米' },
{ 'value': '麦粒', 'label': '麦粒' },
{ 'value': '红薯', 'label': '红薯' },
{ 'value': '腥味商品饵', 'label': '腥味商品饵' },
{ 'value': '香味商品饵', 'label': '香味商品饵' },
{ 'value': '酸臭味商品饵', 'label': '酸臭味商品饵' },
{ 'value': '拟饵', 'label': '拟饵' },
{ 'value': '其他', 'label': '其他', }]

const formRef = ref(null);
const form = ref({
  userId: userId,
  title: '',
  fishType: '',
  fishTypeIndex: '鲤鱼',
  diaogan: '',
  diaoganIndex: '溪流竿',
  yuer: '',
  yuerIndex: '蚯蚓',
  img: [],
  reply: null,
});
const imgList = ref([]);
const rules = {
  title: [
    { required: true, message: '请输入商品标题', trigger: 'blur' }
  ],
  img: [
    { required: true, message: '请上传商品图片', trigger: 'blur' }
  ],
  fish: [
    { required: true, message: '请选择鱼的种类', trigger: 'blur' }
  ],
  diaogan: [
    { required: true, message: '请选择钓竿', trigger: 'blur' }
  ],
  yuer: [
    { required: true, message: '请选择钓竿', trigger: 'blur' }
  ],
};
const handleUploadSuccess = (response, file, fileList) => {
  // console.log(response, file, fileList)
  form.value.img = fileList.map(file => (file.response.virtualPath))
  console.log(form.value.img)
};

const handleRemove = (file, fileList) => {
  // console.log(file, fileList)
  form.value.img = fileList.map(file => (file.response.virtualPath))
  console.log(form.value.img)
}


const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 <= 5;
  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 5MB!');
  }
  return isJPG && isLt2M;
}

const addNewPosts = async () => {
  if (userId) {
    try {
      let tmp = form.value
      tmp.fishType = tmp.fishTypeIndex
      tmp.diaogan = tmp.diaoganIndex
      tmp.yuer = tmp.yuerIndex
      tmp.img = tmp.img.join(',')
      await api.postJson("/addDisscuss", tmp).then(async res => {
        if (res.status == 200) {
          await getData()
          adddialog.value = false
          form.value = {
            userId: userId,
            title: '',
            img: [],
            reply: null,
          }
          imgList.value = []
        } else {
          ElMessage.warning(res.msg)
        }
      })
    } catch (e) {
      console.error(e)
    }
  } else {
    ElMessage.warning("请先登录！")
  }
}
</script>
<style scoped>
.mainBox {
  margin: 20px 400px;
  min-height: 85vh;
}

.ccc {
  display: flex;
  flex-direction: column;
}

.rrr {
  display: flex;
  flex-direction: row;
}

.text_container {
  word-break: break-word;
  white-space: pre-line;
}
</style>
